<template>
    <!-- 后台管理用户 -->
    <!-- lzy 2023年3月14日 14点00分 -->
	<div id="sys_user">
        <el-card style='height:100%'>
            <el-row>
                <el-col :span="4">
                    <el-input v-model="nickName" placeholder="请输入昵称"></el-input>
                </el-col>
                <el-col :span="4">
                    <el-input v-model="loginName" placeholder="请输入登录名"></el-input>
                </el-col>
                <el-col :span="1" style="margin-left: -8px">
                    <el-button
                        @click="getSysUserListAll()"
                        icon="el-icon-search"
                    ></el-button>
                </el-col>
                <el-col :span="4">
                    <!-- 新增弹框按钮 -->
                    <el-button class="saveBtn" @click="saveFormVisible = true" type="success"
                        >添加</el-button
                    >
                </el-col>
            </el-row>
            <el-row style="margin-top: 20px;">
                <el-col>
                    <!-- 用户信息列表 -->
                    <el-table :data='SysUserList' border style='width: 100%;' max-height='700px'>
                        <el-table-column fixed='left' prop='id' label='序号' width='50px'>
                        </el-table-column>
                        <el-table-column prop='nickName' label='用户昵称'>
                        </el-table-column>
                        <el-table-column prop='loginName' label='登录名称'>
                        </el-table-column>
                        <el-table-column prop='roleId' label='角色'>
                            <template slot-scope="scope">
                                <el-col v-for='item in roleList' :key='item.id'>
                                    <el-col v-if="item.id == scope.row.roleId">
                                        {{item.roleName}}
                                    </el-col>
                                </el-col>
                            </template>
                        </el-table-column>
                        <el-table-column prop="createTime" label="创建时间" width="180">
                        </el-table-column>
                        <el-table-column prop="updateTime" label="修改时间" width="180">
                        </el-table-column>
                        <el-table-column fixed='right' label='操作' width='240px'>
                        <template slot-scope='scope'>
                            <el-button
                            @click='openSysUserView(scope.row)'
                            size='small'
                            >查看</el-button
                            >
                            <el-button
                            @click='userFromEditSave(scope.row)'
                            size='small'
                            style="background-color: #534947; color: #fff"
                            >编辑</el-button
                            >
                            <el-button
                            @click='deleteHint(scope.row.id)'
                            size='small'
                            style="background-color: #d7000f; color: #fff"
                            ><i class='el-icon-delete-solid'></i>删除</el-button
                            >
                        </template>
                        </el-table-column>
                    </el-table>
                </el-col>
            </el-row>
            <!-- 分页组件 -->
            <div class='block'>
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage4"
                    :page-sizes="[10, 20, 30, 40]"
                    :page-size="page.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="page.total"
                >
                </el-pagination>
            </div>
        </el-card>
        <!-- 用户新增弹框 -->
        <el-dialog title='新增用户' style="overflow: hidden;" width='30%' :visible.sync='saveFormVisible'>
            <el-form style="width: 600px;" :model='sysUserFrom' ref="sysUserFrom" :rules="sysUserRules">
                <el-form-item label='头像' :label-width='formLabelWidth'>
                    <!-- 文件上传 -->
                    <el-upload
                        class='avatar-uploader'
                        action=''
                        :show-file-list='false'
                        :on-success='handleAvatarSuccess'
                        :before-upload='beforeAvatarUpload'
                    >
                        <img v-if='imageUrl' :src='imageUrl' class='avatar' />
                        <i v-else class='el-icon-plus avatar-uploader-icon'></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label='用户昵称' :label-width='formLabelWidth'>
                    <el-input v-model='sysUserFrom.nickName' autocomplete='off' :style='inputWidth'></el-input>
                </el-form-item>
                <el-form-item label='用户登录名称' :label-width='formLabelWidth' prop="loginName">
                    <el-input v-model='sysUserFrom.loginName' autocomplete='off' :style='inputWidth'></el-input>
                </el-form-item>
                <el-form-item label='密码' :label-width='formLabelWidth'>
                    <el-input v-model='sysUserFrom.password' autocomplete='off' :style='inputWidth'></el-input>
                </el-form-item>
                <el-form-item label='角色' :label-width='formLabelWidth'>
                    <el-select v-model="sysUserFrom.roleId" placeholder="请选择">
                        <el-option
                        v-for="item in roleList"
                        :key="item.id"
                        :label="item.roleName"
                        :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot='footer' class='dialog-footer'>
                <el-button @click='saveFormVisible = false'>取 消</el-button>
                <el-button type='primary' @click="saveSysUser('sysUserFrom')">确 定</el-button>
            </div>
        </el-dialog>
         <!-- 用户新增弹框 -->
        <el-dialog title='新增用户' style="overflow: hidden;" width='30%' :visible.sync='editFormVisible'>
            <el-form style="width: 600px;" :model='editSysUserFrom'>
                <el-form-item label='头像' :label-width='formLabelWidth'>
                        <img v-if='viewImageUrl' :src='viewImageUrl' class='avatar' />
                </el-form-item>
                <el-form-item label='用户昵称' :label-width='formLabelWidth'>
                    <el-input v-model='editSysUserFrom.nickName' autocomplete='off' :style='inputWidth'></el-input>
                </el-form-item>
                <el-form-item label='用户登录名称' :label-width='formLabelWidth' prop="loginName">
                    <el-input v-model='editSysUserFrom.loginName' autocomplete='off' :style='inputWidth'></el-input>
                </el-form-item>
                <el-form-item label='角色' :label-width='formLabelWidth'>
                    <el-select v-model="editSysUserFrom.roleId" placeholder="请选择">
                        <el-option
                        v-for="item in roleList"
                        :key="item.id"
                        :label="item.roleName"
                        :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot='footer' class='dialog-footer'>
                <el-button @click='saveFormVisible = false'>取 消</el-button>
                <el-button type='primary' @click="saveSysUser('sysUserFrom')">确 定</el-button>
            </div>
        </el-dialog>
	</div>
</template>

<script>
export default {
  data () {
    const loginName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入登录账号'))
      } else if (value === this.checkLoginName) {
        callback()
      } else {
        this.$axios.get('/sysUser/checkLoginName?loginName=' + value).then(res => {
          if (res.data.flag) {
            callback(new Error('账号已录入'))
          } else {
            callback()
          }
        })
      }
      	}
    return {
      // 新增用户弹框文本框宽度
      inputWidth: 'width:60%',
      formLabelWidth: '100px',
      // 用户信息列表
      SysUserList: [],
      // 存放角色信息列表
      roleList: [],
      // 用户名 （用于模糊查询）
      nickName: '',
      // 登录名（用于模糊查询）
      loginName: '',
      // 新增用户表单弹框状态
      saveSysUserFormVisible: false,
      // 分页对象
      page: {
        // 每页条数
        pageSize: 10,
        // 分页页数
        pageNum: 1,
        // 分页总条数
        total: 0
      },
      // 分页默认第几页
      currentPage4: 1,
      imageUrl: '',
      imageFile: File,
      // 用户信息表单
      sysUserFrom: {
        // 登录账号
        loginName: '',
        // 账号昵称
        nickName: '',
        // 密码
        password: '',
        // 角色id
        roleId: ''
      },
      // 新增修改校验规则
      sysUserRules: {
        loginName: [
            		{ validator: loginName, trigger: 'blur' }
          		]
      },
      // 用户新增弹框状态
      saveFormVisible: false,
      // 用户查看详情弹框状态
      editFormVisible: false,
      // 用户信息表单
      editSysUserFrom: {
        // 登录账号
        loginName: '',
        // 账号昵称
        nickName: '',
        // 密码
        password: '',
        // 角色id
        roleId: ''
      },
      // 查看详情图片路径
      viewImageUrl: ''
    }
  },
  mounted () {
    // 获取后台用户信息列表
    this.getSysUserListAll()
    // 获取角色信息列表
    this.getRoleList()
  },
  methods: {
    openSysUserView (row) {
      this.editFormVisible = true
      this.viewImageUrl = this.$imageUrl + '?id=' + row.avatarId
      this.editSysUserFrom = row
      console.log(this.viewImageUrl)
    },
    // 新增用户信息
    saveSysUser (formName) {
      const formdata = new FormData()
      formdata.set('nickName', this.sysUserFrom.nickName)
      formdata.set('loginName', this.sysUserFrom.loginName)
      formdata.set('password', this.sysUserFrom.password)
      formdata.set('roleId', this.sysUserFrom.roleId)
      if (this.imageFile.name !== 'File') {
        formdata.set('file', this.imageFile, this.imageFile.name)
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios.post('/sysUser/saveSysUser', formdata)
            .then((res) => {
              if (res.data.flag) {
                this.message('提交成功', 'success')
                this.imageFile = File
                this.imageUrl = ''
                this.saveFormVisible = false // 关闭弹框
                this.sysUserFrom = {
                  // 登录账号
                  loginName: '',
                  // 账号昵称
                  nickName: '',
                  // 密码
                  password: '',
                  // 角色id
                  roleId: ''
                },
                this.getSysUserListAll() // 重新渲染视图
              } else {
                this.message('提交失败，请重试', 'warning')
              }
					 })
        } else {
          return false
        }
      })
    },
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    // 上传文件校验
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isMP3 = file.type === 'image/mp3'
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isJPG && !isPNG && !isMP3) {
        this.$message.error('上传头像图片只能是 JPG 和 PNG 和 MP3 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      this.imageUrl = URL.createObjectURL(file)
      this.imageFile = file
      console.log(this.imageFile)
      return false
    },
    // 删除提示弹框
    deleteHint (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
			    this.deleteSysUserById(id)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 根据id删除用户信息
    deleteSysUserById (id) {
      this.axios.put('/sysUser/deleteSysUserById?id=' + id).then(res => {
        if (res.data.obj > 0) {
          this.message('删除成功', 'success')
          // 初始化渲染视图
          this.getSysUserListAll()
        } else {
          this.message('删除失败', 'warning')
        }
      })
    },
    // 获取角色信息列表
    getRoleList () {
      this.$axios.get('/role/getRoleList').then(res => {
        if (res.data.flag) {
          this.roleList = res.data.obj
        }
      })
    },
    // 获取后台用户信息列表
    getSysUserListAll () {
      this.$axios.get('/sysUser/getSysUserListAll', {
        params: {
          // 登录名
          loginName: this.loginName,
          // 昵称
          nickName: this.nickName,
          pageNum: this.page.pageNum,
          pageSize: this.page.pageSize
        }
      }).then(res => {
        if (res.data.flag) {
          this.SysUserList = res.data.obj.content
          this.page.total = res.data.obj.total
        }
      })
    },
    handleSizeChange (ps) {
      this.page.pageSize = ps
      this.getSysUserListAll()
    },
    handleCurrentChange (pn) {
      this.page.pageNum = pn
      this.getSysUserListAll()
    },
    // 消息提示框方法
    message (message, type) {
      this.$message({
        message: message,
        type: type
      })
    }
  }
}
</script>

<style scoped>
.sys_user{
    width: 100%;
    height: 100%;
}
.saveBtn{
    margin-left:20px;
    background-color: #d7000f;
    border: none;
    text-align: center;
}
/* 图片上传框样式 start */
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    text-align: center;
}
.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    border-radius: 6px;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    border: 1px dashed #d9d9d9;
}
.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
/* 图片上传框样式 end */
</style>
